import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import { Modal, message,Table,Dropdown,Menu,Button,Input ,Row,Col,Select,Form} from 'antd';
const {TextArea} = Input;
const Option = Select.Option;
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import api from '../api';
import moment from 'moment';
import {bind_change} from '../common/State';

import {ISSUE_TYPE} from '../constants/index';


export default class Kefu extends React.Component {
    constructor(props, context){
        super(props, context);
        this.state={
           page:1,
           total:1,
           pageSize:10,
           list:[],
           search:{},
           loading:true,
        };
    }

    componentWillMount(){
        this.doFetch();
    }
    componentWillReceiveProps(nextProps){
        
    }
    async doFetch(page=1){
      let {search} = this.state;

      let result = await api('/operation/kefu/list',{...search,page});

      if(result.cd!=0){
        message.error(result.msg);
        this.setState({loading:false})
        return;
      }
      this.setState({
          page,
          total:result.total,
          list:result.data,
          loading:false
      })
    }

    doSearch(){
      this.setState({
        loading:true
      })
      this.doFetch();
    }

    handleMenuClick(record,e){
      this.context.router.push(`/user/account/list?id=${record.id}&curType=${e.key}`)
    }

    
    //联系用户/查看详情
    async handleIssue(record){
        this.setState({
            visible:true,
            handleRecord:record,
            newKey:Math.random().toString(36).slice(2)
        })
        
    }

    //分页
    toPage({current:page,pageSize,total}){
      this.setState({loading:true})
      this.doFetch(page);
    }
    //关闭客服咨询弹出
    onCloseModal(){
        this.setState({
            content : '',
            contentModal : false
        })
    }

   
    render() {
        var {list, page,total,pageSize,loading,type,visible,handleRecord,newKey}=this.state;
        return (
            <div >
                <NavBar navs={[{title:'客服管理'}]} />
                <ContentBody className='container'>

                  <Table 
                    bordered
                    columns={this.getColumns()} 
                    simple 
                    dataSource={list}
                    pagination={{
                      current:page,
                      total,
                      pageSize,
                      showQuickJumper : true
                    }}
                    loading={loading}
                    onChange={this.toPage.bind(this)}
                    scroll={{ x: 1000 }}
                    rowKey={(record,index) => index}
                  />
                </ContentBody>
                
                <ModalInfoForm 
                    visible = {visible}
                    record = {handleRecord||{}}
                    onOk = {() => {
                        this.setState({loading:true})
                        let {page} = this.state;
                        this.doFetch(page);
                    }}
                    newKey = {newKey}
                    onCancel = {() => {
                        this.setState({visible:false,record:null,newKey:null})
                    }}
                />
                <Modal
                    title="客服咨询内容"
                    
                    visible={this.state.contentModal}
                    footer = {[
                        <Button 
                         key={1}
                         onClick={this.onCloseModal.bind(this)}
                        >关闭</Button>
                    ]}
                    onCancel={this.onCloseModal.bind(this)}
                    >
                    <p>{this.state.content}</p>
                </Modal>
            </div>
        );
    }

    getColumns(){

      let columns = [
            {
              title: '客服ID',
              dataIndex: 'id',
              key: 'id',
            }, {
              title: '用户昵称',
              dataIndex: 'nickname',
              key: 'nickname'
            }, {
              title: '用户手机号',
              dataIndex: 'phone',
              key: 'phone'
            },{
              title: '客服咨询内容',
              dataIndex: 'problem_description',
              key: 'problem_description',
              render:(text) =>{

                if(text&&text.length > 15){
                    return (
                        <a
                            href="javascript:void 0;"
                            onClick = {() => {
                                this.setState({
                                    content:text,
                                    contentModal:true
                                })
                            }}
                        >
                            {text.slice(0,15) + '...'}
                        </a>
                    )
                }
                return text
              }
            },{
              title: '创建时间',
              dataIndex: 'created_at',
              key: 'created_at'
            },{
              title: '完成时间',
              dataIndex: 'completed_at',
              key: 'completed_at'
            },{
              title: '处理人',
              dataIndex: 'processorName',
              key: 'processorName'
            },{
              title: '问题归类',
              dataIndex: 'type',
              key: 'type',
              render:(type,record) => {
                return ISSUE_TYPE[type]
              }
            },{
              title: '完成状态',
              dataIndex: 'status',
              key: 'status',
              render:(status)=>{
                return status==1?'已完成':'未完成'
              }
            },{
              title: '操作',
              key: 'action',
              fixed: 'right',
              width:100,
              render: (record) =>{
                  return (
                        <span>
                            <a 
                                href='javascript:void 0' 
                                onClick = {this.handleIssue.bind(this,record)}
                            >
                            {record.status == 1? "查看详情":"联系用户" }
                            </a>
                        </span>
                      )
              } ,
            }
        ];

        return columns
    }
}

class ModalInfo extends React.Component {
    constructor(props,context){
        super(props, context);
        this.state = {
            confirmLoading:false,
            handleResult:{}
        }
    }
    componentWillMount(){
        
    }

    async componentWillReceiveProps(nextProps) {
        let {record={}} = nextProps;
        if(record.status==1){
            let result  = await api('/operation/kefu/handleResult',{id:record.id});
            if(result.cd!=0){
                message.error(result.msg);
                return
            }
            this.setState({
                handleResult:result.data
            })
        }
    }

    submit(){
        const {validateFieldsAndScroll } = this.props.form;
        validateFieldsAndScroll((errors, values) => {
            if (errors) {
                return
            }
           this.save(values)
        })
    }
    async save(values){
        this.setState({
            confirmLoading:true
        })
        let {onOk,onCancel,record} = this.props;
        let result = await api('/operation/kefu/handleIssue',{id:record.id,...values})
       this.setState({
            confirmLoading:false
        })
        if(result.cd!=0){
            message.error(result.msg);
            return
        }
        onCancel();
        onOk();
        message.success('操作成功')
        
    }
    handleHtml(getFieldDecorator){
        return (
            <form>
                <div className='d-row'>
                    <div className='d-col'>
                        <label>处理结果:</label>
                        <div style={{width:'60%'}}>
                        <Form.Item>
                            {getFieldDecorator('solution', {
                                rules: [{ 
                                    required: true, 
                                    message: '请输入处理结果' 
                                }],
                            })(
                                <TextArea 
                                    size="large" 
                                    autosize={{
                                        minRows:4,
                                        maxRows:6
                                    }}
                                    style={{width:'100%'}}
                                    placeholder="请输入处理结果" 
                                />
                            )}
                        </Form.Item>
                        </div>
                    </div>
                </div>
                <div className='d-row'>
                    <div className='d-col'>
                        <label>问题归类:</label>
                        <div style={{width:'60%'}}>
                        <Form.Item>
                            {getFieldDecorator('type', {
                                rules: [{ 
                                    required: true, 
                                    message: '请选择问题归类' 
                                }],
                                initialValue:""
                            })(
                               <Select
                                style={{ width: '100%' }}
                               >
                                <Option value="">请选择</Option>
                                {Object.keys(ISSUE_TYPE).map((key,index)=>{
                                    return (
                                        <Option value={key} key={index}>{ISSUE_TYPE[key]}</Option>
                                    )
                                })}
                               </Select>
                            )}
                        </Form.Item>
                        </div>
                    </div>
                </div>
            </form>
        )
    }

    render(){
        let {visible,record={},onCancel,newKey} = this.props;
        let {getFieldDecorator} = this.props.form;
        let {confirmLoading,handleResult} = this.state;
        let button = [
            <Button size='large' onClick={onCancel}>取消</Button>
            ,
            <Button size='large' loading={confirmLoading} type="primary" onClick={this.submit.bind(this)}>提交</Button>
        ];
        if(record.status==1){
            button.pop();
        }

        return (
            <Modal 
                key={newKey}
                title={record.stauts==1?"查看详情":"联系用户"}
                visible={visible}
                onCancel={onCancel}
                footer = {button}

            >
            <div className='block-detail-container'>
                <div className='d-row'>
                    <div className='d-col'>
                        <label>用户昵称:</label>
                        <span>{record.nickname||'--'}</span>
                    </div>
                </div>
                <div className='d-row'>
                    <div className='d-col'>
                        <label>手机号:</label>
                        <span>{record.phone||'--'}</span>
                    </div>
                </div>
                <div className='d-row'>
                    <div className='d-col'>
                        <label>问题描述:</label>
                        <span>{record.problem_description||'--'}</span>
                    </div>
                </div>
                {record.status==1?
                    <div>
                        <div className='d-row'>
                            <div className='d-col'>
                                <label>处理结果:</label>
                                <span>{record.solution||'--'}</span>
                            </div>
                        </div>
                        <div className='d-row'>
                            <div className='d-col'>
                                <label>问题归类:</label>
                                <span>{ISSUE_TYPE[record.type]}</span>
                            </div>
                        </div>
                    </div>
                    :this.handleHtml(getFieldDecorator)
                }
            </div>
            </Modal>
        )
    }
}
var ModalInfoForm = Form.create()(ModalInfo);
Kefu.contextTypes= { router: React.PropTypes.object.isRequired};

